<template>
  <ARadioGroup
    v-if="state.tagType == 'radio'"
    @change="handleInput"
    :value="getRadioValue"
    :disabled="disabled"
  >
    <ARadio
      v-for="(item, key) in state.dictOptions"
      :key="key"
      :value="item.value"
    >
      {{ item.label }}
    </ARadio>
  </ARadioGroup>
  <ARadioGroup
    v-else-if="state.tagType == 'radioButton'"
    buttonStyle="solid"
    @change="handleInput"
    :value="getRadioValue"
    :disabled="disabled"
  >
    <ARadioButton
      v-for="(item, key) in state.dictOptions"
      :key="key"
      :value="item.value"
    >
      {{ item.label }}
    </ARadioButton>
  </ARadioGroup>
  <ACheckboxGroup
    v-else-if="state.tagType == 'check'"
    @change="handleInput"
    :value="getCheckboxValue"
    :disabled="disabled"
  >
    <ACheckbox
      v-for="(item, key) in state.dictOptions"
      :key="key"
      :value="item.value"
    >
      {{ item.label }}
    </ACheckbox>
  </ACheckboxGroup>
  <ASelect
    v-else-if="state.tagType == 'select'"
    :allowClear="allowClear"
    :placeholder="placeholder"
    :disabled="disabled"
    :mode="mode === 'multiple' ? 'multiple' : undefined"
    :value="getSelectValue"
    @change="handleInput"
    class="dict-select"
  >
    <ASelectOption
      v-for="(item, key) in state.dictOptions"
      :key="key"
      :value="item.value"
    >
      {{ item.label }}
    </ASelectOption>
  </ASelect>
</template>
<script setup lang="ts" name="DictSelectTagAntd">
import { onMounted, onUnmounted, reactive, watch, computed } from 'vue';
import { DictManager } from '../store/dictStore';
import type { DictOption, FieldMapping } from '../types';

// 导入 Ant Design Vue 组件
import {
  Radio as ARadio,
  RadioGroup as ARadioGroup,
  RadioButton as ARadioButton,
  Checkbox as ACheckbox,
  CheckboxGroup as ACheckboxGroup,
  Select as ASelect,
  SelectOption as ASelectOption,
} from 'ant-design-vue';

const props = defineProps({
  dictCode: { type: String, default: '' },
  dictOptions: { type: Array, default: () => [] as any[] },
  placeholder: { type: String, default: '' },
  disabled: { type: Boolean, default: false },
  allowClear: { type: Boolean, default: false },
  value: { type: [String, Number, Array] },
  type: { type: String, default: '' },
  mode: { type: String, default: '' },
  fieldMapping: { type: Object, default: () => ({} as FieldMapping) },
});

const emits = defineEmits(['update:value', 'change']);

const state = reactive({
  tagType: '',
  dictOptions: [] as DictOption[],
});

// 获取嵌套属性值
const getNestedValue = (obj: any, path: string): any => {
  if (!obj || typeof obj !== 'object' || !path) return undefined;
  try {
    return path.split('.').reduce((current, key) => current?.[key], obj);
  } catch (error) {
    console.warn('DictSelectTagAntd: 获取嵌套属性失败', error);
    return undefined;
  }
};

// 数据转换函数
const transformData = (
  data: any[],
  mapping: FieldMapping = {}
): DictOption[] => {
  if (!Array.isArray(data)) {
    console.warn('DictSelectTagAntd: 数据转换失败，输入不是数组', data);
    return [];
  }

  const { valueKey = 'value', labelKey = 'label' } = mapping;

  try {
    return data.map((item, index) => {
      if (typeof item !== 'object' || item === null) {
        console.warn(`DictSelectTagAntd: 数据项 ${index} 不是有效对象`, item);
        return { value: '', label: '' };
      }

      // 支持嵌套属性访问
      const value =
        getNestedValue(item, valueKey) ?? item[valueKey] ?? item.value ?? '';
      const label =
        getNestedValue(item, labelKey) ??
        item[labelKey] ??
        item.label ??
        item.text ??
        item.name ??
        item.title ??
        '';

      return { value, label };
    });
  } catch (error) {
    console.error('DictSelectTagAntd: 数据转换过程中发生错误', error);
    return [];
  }
};

// 为不同组件类型创建不同的计算属性
const getCheckboxValue = computed(() => {
  if (!props.value) return [];
  return Array.isArray(props.value)
    ? (props.value as (string | number)[])
    : [props.value];
});

const getSelectValue = computed(() => {
  if (!props.value) return undefined;
  if (props.mode === 'multiple') {
    return Array.isArray(props.value)
      ? (props.value as (string | number)[])
      : [props.value];
  }
  return props.value?.toString() || undefined;
});

const getRadioValue = computed(() => {
  if (!props.value) return undefined;
  return props.value?.toString() || undefined;
});

// 监听 dictOptions 变化，优先使用父级传递的 dictOptions
watch(
  () => props.dictOptions,
  (newOptions) => {
    if (newOptions && Array.isArray(newOptions) && newOptions.length > 0) {
      state.dictOptions = transformData(newOptions, props.fieldMapping);
    } else {
      // 如果传入的dictOptions为空或无效，确保使用空数组
      state.dictOptions = [];
    }
  },
  { immediate: true, deep: true }
);

// 监听 fieldMapping 变化，重新转换数据
watch(
  () => props.fieldMapping,
  () => {
    if (
      props.dictOptions &&
      Array.isArray(props.dictOptions) &&
      props.dictOptions.length > 0
    ) {
      state.dictOptions = transformData(props.dictOptions, props.fieldMapping);
    }
  },
  { deep: true }
);

// 监听 dictCode 变化，只有在没有 dictOptions 时才使用 dictCode
watch(
  () => props.dictCode,
  (val: string) => {
    // 只有在没有 dictOptions 或 dictOptions 为空时才使用 dictCode
    if (!props.dictOptions || props.dictOptions.length === 0) {
      initDictData(val);
    }
  },
  { deep: true }
);

onMounted(() => {
  state.tagType = !props.type || props.type === 'list' ? 'select' : props.type;

  // 优先使用 dictOptions，如果没有则使用 dictCode
  if (props.dictOptions && props.dictOptions.length > 0) {
    state.dictOptions = transformData(props.dictOptions, props.fieldMapping);
  } else if (props.dictCode) {
    initDictData(props.dictCode);
  }
});

const initDictData = (code: string) => {
  if (!code) return;
  // 如果已经有 dictOptions 且不为空，则不使用 dictCode
  if (props.dictOptions && props.dictOptions.length > 0) {
    return;
  }

  // 检查字典是否存在，如果存在则获取数据，否则使用空数组
  if (DictManager.hasDict(code)) {
    state.dictOptions = DictManager.getDict(code);
  } else {
    state.dictOptions = [];
  }
};

const handleInput = (e: any) => {
  try {
    const val =
      state.tagType === 'radio' || state.tagType === 'radioButton'
        ? e?.target?.value ?? e
        : e;
    emits('update:value', val);
    emits('change', val);
  } catch (error) {
    console.error('DictSelectTagAntd: 处理输入事件时发生错误', error);
  }
};

// 组件卸载时的清理
onUnmounted(() => {
  // 清理状态
  state.dictOptions = [];
});
</script>

<style scoped>
/* ASelect 宽度自适应 */
.dict-select {
  width: 100%;
  min-width: 0;
}

/* 确保 ASelect 能够继承父容器的宽度 */
.dict-select :deep(.ant-select-selector) {
  width: 100%;
}

/* 多选模式下的宽度自适应 */
.dict-select :deep(.ant-select-selection-overflow) {
  width: 100%;
}

/* 单选模式下的宽度自适应 */
.dict-select :deep(.ant-select-selection-item) {
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 多选模式下的标签宽度自适应 */
.dict-select :deep(.ant-select-selection-item) {
  max-width: calc(100% - 20px);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
